/**
 * 工具Logo处理组合式函数
 * 支持自动降级和错误处理
 */

import { ref } from 'vue'

/**
 * 根据工具名称生成占位Logo
 */
export function getPlaceholderLogo(name: string, size: number = 128): string {
  const colors = [
    '6366F1', // Indigo
    '8B5CF6', // Purple
    'EC4899', // Pink
    'F59E0B', // Amber
    '10B981', // Green
    '3B82F6', // Blue
    'EF4444', // Red
    '06B6D4', // Cyan
  ]
  
  const firstChar = name.charAt(0).toUpperCase()
  const colorIndex = firstChar.charCodeAt(0) % colors.length
  const bgColor = colors[colorIndex]
  
  return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&size=${size}&background=${bgColor}&color=fff&bold=true&font-size=0.4`
}

/**
 * 使用带自动降级的Logo
 */
export function useToolLogo(initialLogo: string, toolName: string) {
  const logoUrl = ref(initialLogo)
  const hasError = ref(false)

  /**
   * 处理图片加载错误
   */
  const handleImageError = (event: Event) => {
    if (hasError.value) return // 避免无限循环

    hasError.value = true
    const img = event.target as HTMLImageElement
    
    // 降级到占位图
    const fallbackUrl = getPlaceholderLogo(toolName, 128)
    img.src = fallbackUrl
    logoUrl.value = fallbackUrl
    
    console.log(`Logo加载失败，已切换到占位图: ${toolName}`)
  }

  /**
   * 重置Logo
   */
  const resetLogo = (newLogo: string) => {
    hasError.value = false
    logoUrl.value = newLogo
  }

  return {
    logoUrl,
    hasError,
    handleImageError,
    resetLogo,
  }
}

/**
 * 直接返回错误处理函数（简化版）
 */
export function useImageError(toolName: string) {
  return (event: Event) => {
    const img = event.target as HTMLImageElement
    if (img.src.includes('ui-avatars.com')) return // 已经是占位图，不再处理
    
    img.src = getPlaceholderLogo(toolName, 128)
  }
}

